package xuesm.proxy.dbroute;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author: xuesm
 * @Description: JDK的动态代理实现分库分表
 * @Date: Create in 20:24 2019/4/4
 */
public class JDKServiceProxy implements InvocationHandler{

	private SimpleDateFormat format = new SimpleDateFormat("yyyy");

	private Object object;
	public Object getInstance(Object object){
		this.object = object;
		Class<?> clazz = object.getClass();
		return Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), this);
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

		before(args);
		Object obj = method.invoke(this.object, args);
		arter();
		return obj;
	}

	private void arter() {
		System.out.println("插入执行完毕， 打日志");
	}

	// 静态代理前执行操作
	private void before(Object[] args) {

		try {
			Order order = (Order) args[0];
			Long time = (Long) order.getClass().getMethod("getCreateTime").invoke(order);
			int year = Integer.parseInt(format.format(new Date(time)));
			System.out.println("静态代理自动分配到DB_【" + year + "】数据源处理数据");
			DynamicDataSourceEntry.set(year);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
